package com.share.netdisk.reclaim.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.netdisk.config.HdfsConfig;
import com.share.netdisk.file.dao.FileDao;
import com.share.netdisk.file.pojo.File;
import com.share.netdisk.garbage.dao.GarbageDao;
import com.share.netdisk.garbage.model.Garbage;
import com.share.netdisk.reclaim.dao.ReclaimDao;
import com.share.netdisk.reclaim.model.Reclaim;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

@Service
public class ReclaimServiceImpl extends ServiceImpl<ReclaimDao, Reclaim> implements ReclaimService{

	@Autowired
	private HdfsConfig hdfsConfig;

	@Autowired
	private ReclaimDao reclaimDao;

	@Autowired
	private GarbageDao garbageDao;

	@Autowired
	private FileDao fileDao;

	//展示列表里的所有内容
	@Override
	public List<File> getFilesByUserId(Integer userId) {
		List<Long> reclaimIds =reclaimDao.selectReclaimIdByUserId(userId);
		if(reclaimIds!=null){
			QueryWrapper<File> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("home_file_id", userId);
			queryWrapper.in("file_id",reclaimIds);
			return fileDao.selectList(queryWrapper);
		}
		return null;
	}

	// 永久删除回收站中的文件（支持批量），基于reclaimId
	@Override
	@Transactional
	public boolean permanentlyDeleteReclaims(List<Integer> reclaimIds) {
		List<Reclaim> reclaims = reclaimDao.selectBatchIds(reclaimIds);

		if (reclaims.isEmpty()) {
			return false; // 如果没有找到任何要删除的回收站记录，则返回false
		}

		FileSystem fs = null;
		int successCount = 0;
		List<Integer> notFoundIds = new java.util.ArrayList<>(reclaimIds); // 记录未找到的ID

		try {
			fs = hdfsConfig.fileSystem();

			for (Reclaim reclaim : reclaims) {
				Integer fileId = reclaim.getFileId();
				Garbage file = garbageDao.selectById(fileId);

				if (file != null && file.getReclaimStatus() == 0) { // 确认文件是否在回收站中
					notFoundIds.remove(reclaim.getReclaimId()); // 移除已找到的ID

					String filePath = file.getFileUrl();
					Path path = new Path(filePath);

					try {
						if (fs.exists(path)) {
							boolean isDeleted = fs.delete(path, true); // 第二个参数表示是否递归删除目录
							if (!isDeleted) {
								throw new IOException("文件删除失败: " + filePath);
							}
							System.out.println("文件删除成功: " + filePath);
						} else {
							System.out.println("文件已不存在: " + filePath);
						}

						// 删除file表中的记录
						garbageDao.deleteById(fileId);

						// 删除reclaim表中的记录
						this.removeById(reclaim.getReclaimId());

						successCount++;
					} catch (IOException e) {
						System.err.println("删除文件时发生错误: " + e.getMessage());
					}
				}
			}

		} catch (IOException | URISyntaxException | InterruptedException e) {
			throw new RuntimeException("HDFS操作失败", e);
		} finally {
			if (fs != null) {
				try {
					fs.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// 如果没有任何文件被成功删除，则认为操作失败
		if (notFoundIds.size() == reclaimIds.size()) {
			System.err.println("所有提供的ID都未找到：" + reclaimIds);
			return false;
		}

		return successCount > 0;
	}
}
